<template>
  <div class="register-container">
    <div class="register-form-wrapper">
      <h1 class="register-title">用户注册</h1>
      <form class="register-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="registerForm.username"
            placeholder="请设置用户名（3-20个字符）"
            required
            class="form-input"
            :class="{ 'input-error': errors.username }"
          />
          <div v-if="errors.username" class="error-text">{{ errors.username }}</div>
        </div>
        
        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            type="email"
            id="email"
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            required
            class="form-input"
            :class="{ 'input-error': errors.email }"
          />
          <div v-if="errors.email" class="error-text">{{ errors.email }}</div>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="registerForm.password"
            placeholder="请设置密码（8-20位，包含字母和数字）"
            required
            class="form-input"
            :class="{ 'input-error': errors.password }"
          />
          <div v-if="errors.password" class="error-text">{{ errors.password }}</div>
        </div>
        
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            type="password"
            id="confirmPassword"
            v-model="registerForm.confirmPassword"
            placeholder="请再次输入密码"
            required
            class="form-input"
            :class="{ 'input-error': errors.confirmPassword }"
          />
          <div v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</div>
        </div>
        
        <div class="form-group">
          <div class="agreement">
            <input type="checkbox" id="agreement" v-model="agreement" required />
            <label for="agreement">
              我已阅读并同意 <a href="#" class="link-primary">用户协议</a> 和 <a href="#" class="link-primary">隐私政策</a>
            </label>
          </div>
          <div v-if="errors.agreement" class="error-text">{{ errors.agreement }}</div>
        </div>
        
        <button type="submit" class="register-button" :disabled="isLoading">
          {{ isLoading ? '注册中...' : '注册' }}
        </button>
        
        <div class="login-link">
          <span>已有账号?</span>
          <router-link to="/login" class="link-primary">立即登录</router-link>
        </div>
      </form>
      
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      
      <!-- 成功提示 -->
      <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()

const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const agreement = ref(false)
const isLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const errors = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreement: ''
})

// 表单验证
const validateForm = () => {
  let isValid = true
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
  
  // 验证用户名
  if (!registerForm.value.username) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (registerForm.value.username.length < 3 || registerForm.value.username.length > 20) {
    errors.username = '用户名长度应为3-20个字符'
    isValid = false
  }
  
  // 验证邮箱
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!registerForm.value.email) {
    errors.email = '请输入邮箱地址'
    isValid = false
  } else if (!emailRegex.test(registerForm.value.email)) {
    errors.email = '请输入有效的邮箱地址'
    isValid = false
  }
  
  // 验证密码
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/
  if (!registerForm.value.password) {
    errors.password = '请设置密码'
    isValid = false
  } else if (!passwordRegex.test(registerForm.value.password)) {
    errors.password = '密码长度应为8-20位，并包含字母和数字'
    isValid = false
  }
  
  // 验证确认密码
  if (!registerForm.value.confirmPassword) {
    errors.confirmPassword = '请确认密码'
    isValid = false
  } else if (registerForm.value.confirmPassword !== registerForm.value.password) {
    errors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  // 验证用户协议
  if (!agreement.value) {
    errors.agreement = '请阅读并同意用户协议和隐私政策'
    isValid = false
  }
  
  return isValid
}

const handleRegister = async () => {
  // 清除之前的提示信息
  errorMessage.value = ''
  successMessage.value = ''
  
  // 验证表单
  if (!validateForm()) {
    return
  }
  
  isLoading.value = true
  
  try {
    const userData = {
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password
    }
    
    const result = await userStore.register(userData)
    
    if (result.success) {
      // 注册成功
      successMessage.value = '注册成功，请登录！'
      
      // 重置表单
      registerForm.value = {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
      agreement.value = false
      
      // 2秒后跳转到登录页面
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else {
      errorMessage.value = '注册失败，请稍后重试'
    }
  } catch (error) {
    console.error('注册错误:', error)
    errorMessage.value = '注册失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  padding: 20px;
}

.register-form-wrapper {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
}

.register-title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 30px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.1);
}

.input-error {
  border-color: #d32f2f !important;
}

.error-text {
  color: #d32f2f;
  font-size: 12px;
  margin-top: 4px;
}

.agreement {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 24px;
}

.agreement input {
  margin-top: 2px;
}

.agreement label {
  margin: 0;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  flex: 1;
}

.link-primary {
  color: #4285f4;
  text-decoration: none;
  font-weight: 500;
}

.link-primary:hover {
  text-decoration: underline;
}

.register-button {
  width: 100%;
  padding: 14px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.register-button:hover:not(:disabled) {
  background-color: #3367d6;
}

.register-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.error-message {
  margin-top: 16px;
  padding: 12px;
  background-color: #fee;
  color: #d32f2f;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
}

.success-message {
  margin-top: 16px;
  padding: 12px;
  background-color: #efe;
  color: #388e3c;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
}

@media (max-width: 480px) {
  .register-form-wrapper {
    padding: 30px 20px;
  }
  
  .register-title {
    font-size: 20px;
  }
  
  .form-input {
    padding: 10px 14px;
    font-size: 14px;
  }
  
  .register-button {
    padding: 12px;
    font-size: 14px;
  }
}
</style>